<?php
require_once 'classes/Database.php';
require_once 'classes/ProductManager.php';
require_once 'classes/OrderManager.php';
require_once 'classes/EasyPay.php';
require_once 'classes/SettingsHelper.php';

$productManager = new ProductManager();
$orderManager = new OrderManager();
$easyPay = new EasyPay();
$siteName = getSiteName();

$productId = $_GET['id'] ?? 0;
$product = $productManager->getProductById($productId);

if (!$product) {
    header('Location: index.php');
    exit;
}

$error = '';
$success = '';

// 处理购买请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $contactInfo = trim($_POST['contact_info'] ?? '');
    $paymentType = $_POST['payment_type'] ?? 'alipay';
    
    if (empty($contactInfo)) {
        $error = '请输入联系方式';
    } elseif (!$productManager->checkStock($productId)) {
        $error = '商品库存不足';
    } else {
        try {
            // 创建订单
            $orderResult = $orderManager->createOrder(
                $productId,
                $product['price'], // 金额
                $contactInfo,      // 联系方式
                $paymentType,      // 支付方式
                0                  // 用户ID，0表示游客
            );
            
            if ($orderResult) {
                // 创建支付请求
                $paymentResult = $easyPay->createPayment(
                    $orderResult['order_no'],
                    $product['price'],
                    $paymentType,
                    $product['name']
                );
                
                // 重定向到支付页面
                header('Location: ' . $paymentResult['payment_url']);
                exit;
            } else {
                $error = '订单创建失败，请重试';
            }
        } catch (Exception $e) {
            $error = '系统错误：' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购买商品 - <?php echo htmlspecialchars($siteName); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .product-info {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
        }
        .price-tag {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 10px 20px;
            border-radius: 25px;
            font-size: 1.5rem;
            font-weight: bold;
        }
        .btn-pay {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            color: white;
            padding: 12px 30px;
            font-size: 1.1rem;
        }
        .btn-pay:hover {
            background: linear-gradient(45deg, #764ba2, #667eea);
            color: white;
        }
        .payment-method {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .payment-method:hover, .payment-method.selected {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        .payment-icon {
            font-size: 1.5rem;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <!-- 导航 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <i class="fas fa-shopping-cart me-2"></i><?php echo htmlspecialchars($siteName); ?>
            </a>
            <a href="index.php" class="btn btn-outline-light">
                <i class="fas fa-arrow-left me-2"></i>返回商品列表
            </a>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <!-- 错误提示 -->
                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i><?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- 成功提示 -->
                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- 商品信息 -->
                <div class="product-info text-center">
                    <h2 class="mb-3"><?php echo htmlspecialchars($product['name']); ?></h2>
                    <p class="lead mb-4"><?php echo htmlspecialchars($product['description']); ?></p>
                    <div class="price-tag d-inline-block">
                        ¥<?php echo number_format($product['price'], 2); ?>
                    </div>
                    <div class="mt-3">
                        <span class="badge bg-success">
                            <i class="fas fa-box me-1"></i>库存: <?php echo $product['stock']; ?>
                        </span>
                    </div>
                </div>

                <!-- 购买表单 -->
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h4 class="mb-0">
                            <i class="fas fa-credit-card me-2"></i>购买信息
                        </h4>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="buyForm">
                            <!-- 联系方式 -->
                            <div class="mb-4">
                                <label for="contact_info" class="form-label">
                                    <i class="fas fa-envelope me-2"></i>联系方式（用于接收CDK码）
                                </label>
                                <input type="text" class="form-control form-control-lg" id="contact_info" name="contact_info" 
                                       placeholder="请输入您的邮箱或手机号" required
                                       value="<?php echo htmlspecialchars($_POST['contact_info'] ?? ''); ?>">
                                <div class="form-text">购买成功后，CDK码将发送到此联系方式</div>
                            </div>

                            <!-- 支付方式 -->
                            <div class="mb-4">
                                <label class="form-label">
                                    <i class="fas fa-wallet me-2"></i>选择支付方式
                                </label>
                                <?php
                                $paymentMethods = $easyPay->getSupportedPayments();
                                $selectedPayment = $_POST['payment_type'] ?? 'alipay';
                                ?>
                                <?php foreach ($paymentMethods as $key => $name): ?>
                                    <div class="payment-method <?php echo $selectedPayment === $key ? 'selected' : ''; ?>" 
                                         onclick="selectPayment('<?php echo $key; ?>')">
                                        <input type="radio" class="form-check-input" name="payment_type" 
                                               value="<?php echo $key; ?>" 
                                               <?php echo $selectedPayment === $key ? 'checked' : ''; ?> 
                                               style="display: none;">
                                        <?php
                                        $icons = [
                                            'alipay' => 'fab fa-alipay text-primary',
                                            'wxpay' => 'fab fa-weixin text-success',
                                            'qqpay' => 'fab fa-qq text-info',
                                            'bank' => 'fas fa-university text-warning'
                                        ];
                                        ?>
                                        <i class="<?php echo $icons[$key] ?? 'fas fa-money-bill-wave'; ?> payment-icon"></i>
                                        <strong><?php echo $name; ?></strong>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <!-- 订单确认 -->
                            <div class="mb-4">
                                <div class="alert alert-info">
                                    <h6><i class="fas fa-info-circle me-2"></i>购买须知：</h6>
                                    <ul class="mb-0">
                                        <li>支付成功后，系统将自动发放CDK码</li>
                                        <li>CDK码将通过您提供的联系方式发送</li>
                                        <li>请妥善保管CDK码，遗失不补</li>
                                        <li>如有问题，请联系客服</li>
                                    </ul>
                                </div>
                            </div>

                            <!-- 提交按钮 -->
                            <div class="d-grid">
                                <button type="submit" class="btn btn-pay btn-lg">
                                    <i class="fas fa-lock me-2"></i>立即支付 ¥<?php echo number_format($product['price'], 2); ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function selectPayment(type) {
            // 移除所有选中状态
            document.querySelectorAll('.payment-method').forEach(function(el) {
                el.classList.remove('selected');
            });
            
            // 添加当前选中状态
            event.currentTarget.classList.add('selected');
            
            // 设置radio选中
            document.querySelector('input[name="payment_type"][value="' + type + '"]').checked = true;
        }

        // 表单提交验证
        document.getElementById('buyForm').addEventListener('submit', function(e) {
            const contactInfo = document.getElementById('contact_info').value.trim();
            if (!contactInfo) {
                e.preventDefault();
                alert('请输入联系方式');
                return false;
            }
            return true;
        });
    </script>
</body>
</html>
